package com.chalk.config.security;

import com.chalk.common.constant.CommonConstants;
import com.chalk.common.constant.ResultConstants;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * ClassName: CustomAuthExceptionEntryPoint 该异常实现了很多子类。子类都是涉及到权限校验问题的。
 *
 * @author L.G
 * @Description 自定义认证异常信息
 * @email lg10000@126.com
 * @date 2018年8月2日 下午4:58:42
 */
@Component
public class CustomAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private ObjectMapper objectMapper;

    @SuppressWarnings("static-access")
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws IOException, ServletException {
        Result result = Result.success();
        Throwable cause = authException.getCause();
        response.setCharacterEncoding(CommonConstants.UTF8);
        response.setContentType(CommonConstants.CONTENT_TYPE);
        if (authException instanceof AuthenticationException) {
            result = Result.custom(ResultConstants.TOKEN_INVALID_CODE, "无效的令牌", null);
        } else {
            result = Result.custom(ResultCode.NOT_LOGIN.code(),ResultCode.NOT_LOGIN.msg(), null);
        }
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        PrintWriter printWriter = response.getWriter();
        printWriter.append(objectMapper.writeValueAsString(result));
    }

}
